#ifndef __LSTATI_2D_ARRAY_H__
#define __LSTATI_2D_ARRAY_H__


#include "../CoreMacro.h"

NS_CC_CORE_BEGIN

template<typename T>
class LStatic2DArray
{
public:
	LStatic2DArray( ) :
		m_pData(0),
		m_iRow(0),
		m_iCol(0)
	{

	}

	virtual ~LStatic2DArray( )
	{
		clearData( );
		clear( );
	}

	inline
	static LStatic2DArray<T>*	create( int row , int col )
	{
		LStatic2DArray<T>* pArr2D = new LStatic2DArray();
		pArr2D->init( row , col );

		return pArr2D;
	}

	void	init ( int row , int col )
	{
		if( m_pData )
		{
			//Clear data
			clearData();
			clear( );
		}
		int i , j;
		m_iRow = row;
		m_iCol = col;

		m_pData = new T**[m_iRow];

		for( i = 0 ; i < m_iRow ; ++i )
		{
			m_pData[i] = new T*[m_iCol];
			for( j = 0 ; j < m_iCol ; ++j )
			{
				m_pData[i][j] = 0;
			}
		}
	}

	void	addObject		( T* pObject , int row , int col , bool isClearOldData = true )
	{
		if( checkIsOutOfBound(row,col) )
			return;

		removeObject(row,col,isClearOldData);

		m_pData[row][col] = pObject;
	}

	T*	getObject		( int row , int col )
	{
		if( checkIsOutOfBound(row,col) )
			return 0;

		return m_pData[row][col];
	}

	//Return object if we dont want to release it otherwise it return NULL
	T*	removeObject	( int row , int col , bool isRelease = true )
	{
		if( checkIsOutOfBound(row,col) )
			return 0;

		T* pData = 0;

		do
		{
			if( isRelease )
				delete m_pData[row][col];
			else
				pData = m_pData[row][col];
			m_pData[row][col] = 0;
		}while(0);

		return pData;
	}

	void	clearData ( bool isRelease = true )
	{
		int i , j ;

		for( i = 0 ; i < m_iRow ; ++i )
		{
			for( j = 0 ; j < m_iCol ; ++j )
			{
				do{
					if( isRelease )
						delete m_pData[i][j];
					m_pData[i][j] = 0;
				}while(0);
			}
		}
	}

	void	clear (  )
	{
		for( int i = 0 ; i < m_iRow ; ++i )
		{
			do
			{
				delete[] m_pData[i];
				m_pData[i] = 0;
			}while(0);
		}

		do{
			delete[] m_pData;
		}while(0);

		m_pData = 0;

		m_iRow = m_iCol = 0;
	}

	

	int		getNumRow	( )
	{
		return m_iRow;
	}

	int		getNumCol	( )
	{
		return m_iCol;
	}

private:
	T***			m_pData;
	int				m_iRow;
	int				m_iCol;

	bool	checkIsOutOfBound		( int row , int col )
	{
		return row < 0 || row >= m_iRow || col < 0 || col >= m_iCol;
	}
};

NS_CC_CORE_END



#endif //__LSTATI_2D_ARRAY_H__